<template>
  <el-form ref="fromRef" :model="loginForm" :rules="rules" size="large" @keyup.enter="handleLogin">
    <el-form-item prop="account">
      <el-input v-model="loginForm.account" placeholder="用户名">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="passWord">
      <el-input v-model="loginForm.passWord" type="password" placeholder="密码" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-input v-model="loginForm.code" placeholder="验证码">
        <template #prefix>
          <el-icon class="el-input__icon">
            <Picture />
          </el-icon>
        </template>
        <template #suffix>
          <img :src="'data:image/gif;base64,' + base64Str" alt="" style="cursor: pointer" @click="changeVerifCode" />
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm"> 重置 </el-button>
    <el-button :loading="loading" :icon="UserFilled" round size="large" type="primary" @click="handleLogin"> 登录 </el-button>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import type { Login } from "@/api/interface";
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { encryptSM2 } from "@/utils/sm2Crypto";
import { ElNotification, ElMessage } from "element-plus";
import { getVerifCodeApi, loginApi } from "@/api/modules/system/login";
import { getLoginUserInfoApi } from "@/api/modules/system";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

/** 表单实例 */
const fromRef = ref<FormInstance>();
/** 表单校验规则 */
const rules = reactive<FormRules>({
  account: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  passWord: [{ required: true, message: "请输入密码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});

/** 验证码 */
const base64Str = ref("");
/** 登录状态 */
const loading = ref(false);
/** 登录表单数据 */
const loginForm = reactive<Login.LoginForm>({
  account: "",
  passWord: "",
  code: "",
  codeId: ""
});

/** 获取验证码 */
const changeVerifCode = () => {
  /** 清空验证码信息 */
  loginForm.code = "";
  loginForm.codeId = "";
  getVerifCodeApi().then(({ data }) => {
    base64Str.value = data.base64;
    loginForm.codeId = data.id;
  });
};

/** 登录事件 */
const handleLogin = () => {
  fromRef.value
    // 1. 表单校验
    ?.validate()
    // 1.1 验证失败时结束调用链
    .catch(() => {
      return Promise.reject(new Error("表单校验失败！"));
    })
    // 2. 加载状态开启、加密密码
    .then(() => {
      loading.value = true;
      return encryptSM2(loginForm.passWord);
    })
    // 3. 执行登录接口
    .then(passWord => {
      return loginApi({ ...loginForm, passWord: passWord });
    })
    // 4. 保存 token、获取用户信息
    .then(({ data }) => {
      userStore.setToken(data.accessToken, data.refreshToken);
      return getLoginUserInfoApi();
    })
    // 5. 保存用户信息、添加动态路由
    .then(({ data }) => {
      userStore.setUserInfo(data);
      return initDynamicRouter();
    })
    // 6. 跳转到首页
    .then(() => {
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录 Canroc.Net 后台管理系统！",
        type: "success",
        duration: 3000
      });
    })
    // 7. 异常处理、重新获取验证码
    .catch((error: Error) => {
      console.error(error);
      if (error.message != "表单校验失败！") {
        changeVerifCode();
        ElMessage.error({ message: "登录失败！" });
      }
    })
    // 8. 加载状态关闭
    .finally(() => {
      loading.value = false;
    });
};

/** 重置事件 */
const resetForm = () => {
  fromRef.value?.resetFields();
};

onMounted(() => {
  changeVerifCode();
});
</script>

<style scoped lang="scss">
@use "../index";
</style>
